package vashion.azeroth.core.manager.item;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.common.NeedOperateFlow;
import vashion.azeroth.core.common.NeedPermission;
import vashion.azeroth.core.item.pojo.ForestPropertyValueDO;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.pojo.PropertyValueDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.manager.forest.BaseForestPropertyManager;
import vashion.azeroth.core.pojo.common.OperateFlowEnum;
import vashion.azeroth.core.result.ApiResult;

/**
 * Created by tingting on 15/8/31. 商品写接口
 */
@Service
public class ItemWriteManager {

	private final static Logger log = LoggerFactory.getLogger(ItemWriteManager.class);

	@Autowired
	private BaseItemManager baseItemManager;

	@Autowired
	private BaseItemSkuManager baseItemSkuManager;

	@Autowired
	private BaseForestPropertyManager baseForestPropertyManager;

	@Autowired
	private ItemTagManager itemTagManager;

	/**
	 * 发布商品
	 *
	 * @param itemDO
	 * @param skuDOList
	 * @param tagListString
	 * @param operateId
	 *            操作者id，只有运营可以发布商品
	 * @return
	 */
	// @NeedPermission(operateIdArgLocation = 3)
	@NeedOperateFlow(operateIdArgLocation = 3, operateFlowEnum = OperateFlowEnum.ITEM)
	public ApiResult<Boolean> publishItem(ItemDO itemDO, List<ItemSkuDO> skuDOList, String tagListString,
			long operateId) {

		itemDO.setGmtCreate(new Date());
		itemDO.setGmtModified(new Date());
		itemDO.setSpecialGmtModified(new Date());
		itemDO.setStatus(ItemStatusEnum.ORIGIN_STATUS.getStatus());
		// 权限等校验
		ItemErrorEnum itemErrorEnum = checkBaseProperty(itemDO);
		if (null == itemErrorEnum) {
			itemErrorEnum = checkExtraProperty(itemDO);
		}
		if (null != itemErrorEnum) {
			return ApiResult.newErrorResult(itemErrorEnum.getErrorCode(), itemErrorEnum.getErrorMessage());
		}
		try {
			Long saveResult = baseItemManager.saveWithId(itemDO);
			if (saveResult > 0 && itemDO.getId() > 0) {
				if (null == tagListString) {
					itemTagManager.addDefaultTagsForItem(itemDO, operateId);
				} else {
					itemTagManager.updateTagsForItem(itemDO.getId(), tagListString, operateId, true);
				}
			}
		} catch (Exception e) {
			log.error("baseItemManager.save item error,itemDO=" + itemDO, e);
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
					ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		if (CollectionUtils.isEmpty(skuDOList)) {
			return ApiResult.newSuccessResult(true);
		}
		// 写入sku
		for (ItemSkuDO skuDO : skuDOList) {
			skuDO.setItemId(itemDO.getId());
		}
		ApiResult<Boolean> skuResult = baseItemSkuManager.batchSave(skuDOList);
		if (!skuResult.isSuccess()) {
			return skuResult;
		}
		// //写入erp
		// AddItemRequest addItemRequest = buildRequest(itemDO, skuDOList);
		// AddItemResponse addItemResponse =
		// apiItemService.addItem(addItemRequest);
		// if (addItemResponse.isSuccess()) {
		// return ApiResult.newSuccessResult(true);
		// } else {
		// log.error("item save error ,sync erp error ,itemDO=" + itemDO +
		// ",addItemResponse=" + addItemResponse.getErrorCode() + "," +
		// addItemResponse.getErrorDesc());
		// return
		// ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
		// ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
		// }
		return ApiResult.newSuccessResult(true);
	}

	// private AddItemRequest buildRequest(ItemDO itemDO, List<ItemSkuDO>
	// skuDOList) {
	// AddItemRequest addItemRequest = new AddItemRequest();
	// addItemRequest.setName(itemDO.getTitle());
	// addItemRequest.setCategoryCode("" + itemDO.getCategoryId());
	// addItemRequest.setSalesPrice(MoneyUtil.fenToYuanDouble(itemDO.getPrice()));
	// addItemRequest.setCode("" + itemDO.getId());
	// if (!CollectionUtils.isEmpty(skuDOList)) {
	// List<Sku> skuList = Lists.newArrayList();
	// for (ItemSkuDO itemSkuDO : skuDOList) {
	// Sku sku = new Sku();
	// sku.setSkuCode("" + itemSkuDO.getId());
	// sku.setSkuId("" + itemSkuDO.getId());
	// sku.setSkuSalesPrice(MoneyUtil.fenToYuan(itemSkuDO.getPrice()));
	// sku.setSkuName("default");
	// skuList.add(sku);
	// }
	// addItemRequest.setSkus(skuList);
	// }
	// return addItemRequest;
	// }

	/**
	 * @param operateId
	 *            操作者id，只有运营可以发布商品
	 * @param itemDO
	 * @param tagListString
	 * @return
	 */
	@NeedPermission(operateIdArgLocation = 1)
	@NeedOperateFlow(operateIdArgLocation = 1, operateFlowEnum = OperateFlowEnum.ITEM)
	public ApiResult<Boolean> updateItem(ItemDO itemDO, String tagListString, long operateId) {
		ItemErrorEnum itemErrorEnum = checkBaseProperty(itemDO);
		if (null != itemErrorEnum) {
			return ApiResult.newErrorResult(itemErrorEnum.getErrorCode(), itemErrorEnum.getErrorMessage());
		}
		ItemDO originItemDO = baseItemManager.get(itemDO.getId());
		if (null == originItemDO) {
			return ApiResult.newErrorResult(ItemErrorEnum.NOT_EXITS.getErrorCode(),
					ItemErrorEnum.NOT_EXITS.getErrorMessage());
		}
		try {
			// 如果商品描述有修改，修改SpecialGmtModified
			if (null != itemDO.getItemDesc() && !itemDO.getItemDesc().equalsIgnoreCase(originItemDO.getItemDesc())) {
				itemDO.setSpecialGmtModified(new Date());
			}
			if (baseItemManager.update(itemDO) > 0) {
				// FIXME

				// 更新erp
				// AddItemRequest addItemRequest = buildRequest(itemDO, null);
				if (null != tagListString) {
					itemTagManager.updateTagsForItem(itemDO.getId(), tagListString, operateId, true);
				}
			}
		} catch (Exception e) {
			log.error("baseItemManager.update error,itemDO=" + itemDO, e);
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
					ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(true);
	}

	/**
	 * 删除商品
	 *
	 * @param itemId
	 * @param operateId
	 *            只有运营可以删除商品
	 * @return
	 */
	@NeedPermission(operateIdArgLocation = 1)
	@NeedOperateFlow(operateIdArgLocation = 1, operateFlowEnum = OperateFlowEnum.ITEM)
	public ApiResult<Boolean> deleteItem(long itemId, long operateId) {

		ItemDO itemDO = baseItemManager.get(itemId);
		if (null == itemDO) {
			return ApiResult.newErrorResult(ItemErrorEnum.ITEM_IS_NULL.getErrorCode(),
					ItemErrorEnum.ITEM_IS_NULL.getErrorMessage());
		}
		boolean updateSuccess;
		try {
			itemDO.setStatus(ItemStatusEnum.SELF_DELETE.getStatus());
			updateSuccess = baseItemManager.update(itemDO) > 0;
		} catch (Exception e) {
			log.error("baseItemManager.updateItemStatus error, itemId=" + itemId, e);
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
					ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return updateSuccess ? ApiResult.newSuccessResult(true)
				: ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
						ItemErrorEnum.SYSTEM_ERROR.getErrorMessage(), false);
	}

	/**
	 * 恢复商品
	 *
	 * @param itemId
	 * @param operateId
	 *            只有运营可以恢复商品
	 * @return
	 */
	@NeedPermission(operateIdArgLocation = 1)
	@NeedOperateFlow(operateIdArgLocation = 1, operateFlowEnum = OperateFlowEnum.ITEM)
	public ApiResult<Boolean> resumeItem(long itemId, long operateId) {

		ItemDO itemDO = baseItemManager.get(itemId);
		if (null == itemDO) {
			return ApiResult.newErrorResult(ItemErrorEnum.ITEM_IS_NULL.getErrorCode(),
					ItemErrorEnum.ITEM_IS_NULL.getErrorMessage());
		}
		boolean updateSuccess;
		try {
			itemDO.setStatus(ItemStatusEnum.ORIGIN_STATUS.getStatus());
			updateSuccess = baseItemManager.update(itemDO) > 0;
		} catch (Exception e) {
			log.error("baseItemManager.updateItemStatus error, itemId=" + itemId, e);
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
					ItemErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return updateSuccess ? ApiResult.newSuccessResult(true)
				: ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
						ItemErrorEnum.SYSTEM_ERROR.getErrorMessage(), false);
	}

	/**
	 * 检查其他属性
	 *
	 * @param itemDO
	 * @return
	 */
	private ItemErrorEnum checkExtraProperty(ItemDO itemDO) {

		if (null == itemDO || StringUtils.isEmpty(itemDO.getItemDesc()) || itemDO.getUserId() <= 0
				|| itemDO.getCategoryId() <= 0 || itemDO.getPrice() <= 0
				|| StringUtils.isEmpty(itemDO.getPriceCurno())) {
			return ItemErrorEnum.ITEM_ARG_ERROR;
		}
		if (haveIllegalWord(itemDO.getItemDesc())) {
			return ItemErrorEnum.CONTAINS_ILLEGAL_WORD;
		}
		return null;
	}

	/**
	 * 检查基础属性
	 *
	 * @param itemDO
	 * @return
	 */
	private ItemErrorEnum checkBaseProperty(ItemDO itemDO) {

		if (null == itemDO) {
			return ItemErrorEnum.ITEM_ARG_ERROR;
		}
		if (haveIllegalWord(itemDO.getItemDesc())) {
			return ItemErrorEnum.CONTAINS_ILLEGAL_WORD;
		}
		// KFC校验
		return null;
	}

	private boolean haveIllegalWord(String value) {
		if (StringUtils.isBlank(value)) {
			return false;
		}
		return false;
	}

	/**
	 * 处理Sku发生变更时的回调
	 *
	 * @param itemId
	 * @param skuChangeNum
	 *            sku变动个数
	 * @param stockCount
	 *            sku总数
	 * @param isAdd
	 * @return
	 */
	public boolean processSkuNumChange(long itemId, int skuChangeNum, int stockCount, boolean isAdd) {

		return baseItemManager.updateSkuAndSale(itemId, isAdd ? 0 : skuChangeNum, stockCount);
	}

	/**
	 * 更新一个商品的sku的库存量
	 * 
	 * @param itemCode
	 * @param propertyValueDOList
	 * @param memberId
	 * @param operateId
	 * @return 更新结果
	 */
	@NeedPermission(operateIdArgLocation = 3)
	@NeedOperateFlow(operateIdArgLocation = 3, operateFlowEnum = OperateFlowEnum.ITEM)
	public boolean updateItemSku(String itemCode, List<PropertyValueDO> propertyValueDOList, Long memberId,
			long operateId) {
		// 查询出要更新的商品
		ItemQueryDO itemDoByItemCode = new ItemQueryDO();
		itemDoByItemCode.setItemCode(itemCode);
		itemDoByItemCode.setUserId(memberId);
		List<ItemDO> itemList = baseItemManager.querySameCodeItem(itemDoByItemCode);
		// 检查商品数量是否为1
		if (!CollectionUtils.hasUniqueObject(itemList)) {
			return false;
		}
		ItemDO item = itemList.get(0);
		int totalStock = item.getStock();
		boolean result = false;
		// 查询商品的SKU
		ApiResult<ForestPropertyValueDO> ForestPropertyResult = baseForestPropertyManager
				.getForestPropertyValues(item.getCategoryId(), AzerothConstants.ItemForestProperty.NORMAL);
		if (null != ForestPropertyResult && ForestPropertyResult.isSuccess()
				&& null != ForestPropertyResult.getData()) {
			ForestPropertyValueDO forestPropertyValueDO = ForestPropertyResult.getData();
			List<PropertyValueDO> propertyValueDOListOrigial = forestPropertyValueDO.getPropertyValueDOList();

			for (PropertyValueDO propertyValueDOTemp : propertyValueDOList) {
				// 查询商品的property value
				PropertyValueDO propertyValueDO = new PropertyValueDO();
				// 只有一个默认尺寸，并且没有指明
				if (StringUtils.isBlank(propertyValueDOTemp.getValue()) && 1 == propertyValueDOList.size()
						&& 1 == propertyValueDOListOrigial.size()) {
					propertyValueDO = propertyValueDOListOrigial.get(0);
					// 如果尺寸为0，下架商品
					if (0 == propertyValueDOTemp.getStock()) {
						this.deleteItem(item.getId(), operateId);
						break;
					}
				}
				// 正常情况
				if (StringUtils.isNotBlank(propertyValueDOTemp.getValue())) {
					for (PropertyValueDO propertyValueDOOrigialTemp : propertyValueDOListOrigial) {
						if (propertyValueDOTemp.getValue().equalsIgnoreCase(propertyValueDOOrigialTemp.getValue())) {
							propertyValueDO = propertyValueDOOrigialTemp;
						}
					}
					// 查询出对于的SKU
					ItemSkuDO itemSkuDO = new ItemSkuDO();
					itemSkuDO.setItemId(item.getId());
					itemSkuDO.setPropertyValueIdArr(String.valueOf(propertyValueDO.getId()));
					List<ItemSkuDO> itemSkuList = baseItemSkuManager.find(itemSkuDO);
					if (!CollectionUtils.hasUniqueObject(itemSkuList)) {
						continue;
					}
					itemSkuDO = itemSkuList.get(0);
					// 更新sku的库存
					long originalStock = itemSkuDO.getStock();
					itemSkuDO.setStock(propertyValueDOTemp.getStock());
					result = baseItemSkuManager.update(itemSkuDO) > 0;
					if (result) {
						totalStock = (int) (totalStock - originalStock + propertyValueDOTemp.getStock());
					}
				}
			}
			// 更新商品的总库存
			ItemDO itemUpdate = new ItemDO();
			itemUpdate.setId(item.getId());
			itemUpdate.setStock(totalStock);
			result = this.updateItem(itemUpdate, null, item.getUserId()).isSuccess();
		}
		return result;
	}
}
